package com.letter.otools.day.diary;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;


import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.textfield.TextInputEditText;
import com.letter.otools.day.BaseActivity;
import com.letter.otools.day.R;
import com.letter.otools.day.util.FkhUriFixUtils;
import com.letter.otools.day.util.ImageUtils;
import com.letter.otools.day.util.StringUtils;
import com.letter.otools.day.util.UriUtils;
import com.letter.otools.day.view.flowlayout.FlowLayout;
import com.letter.otools.day.view.flowlayout.TagAdapter;
import com.letter.otools.day.view.flowlayout.TagFlowLayout;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class DiaryAddActivity extends BaseActivity implements View.OnClickListener {
    private MaterialToolbar toolbar;
    private TextInputEditText etTitle;
    private TextInputEditText etContent;
    private String selectDay;
    private AppCompatButton pickImage;

    //最多上传4张图片
    protected static final int PIC_MAX_LIMIT = 4;
    List<String> billImages = new ArrayList<>();
    TagAdapter<String> tagAdapter;
    protected static final String ADD_TAG = "add";
    private TagFlowLayout addImage;

    //待编辑的日记ID
    private Diary diary;
    private int diaryId = -1;

    void initImagePick() {
        //添加按钮
        billImages.add(ADD_TAG);
        addImage.setAdapter(tagAdapter = new TagAdapter<String>(billImages) {
            @Override
            public View getView(FlowLayout parent, int position, String image) {
                View view = getLayoutInflater().inflate(R.layout.item_add_image, addImage, false);
                initImageView(view, image, position);
                return view;
            }
        });
    }

    public void initImageView(View view, String image, int position) {
        if (ADD_TAG.equals(image)) {
            view.findViewById(R.id.addImageLay).setVisibility(View.VISIBLE);
            view.findViewById(R.id.imageLay).setVisibility(View.GONE);
            view.findViewById(R.id.addImageLay).setOnClickListener(view1 -> {
                pickImage();
            });
        } else {
            view.findViewById(R.id.addImageLay).setVisibility(View.GONE);
            view.findViewById(R.id.imageLay).setVisibility(View.VISIBLE);
            ImageUtils.showImage(getActivity(), image, view.findViewById(R.id.image));
            view.findViewById(R.id.deleteImg).setOnClickListener(view1 -> {
                billImages.remove(position);
                tagAdapter.notifyDataChanged();
            });
        }
    }

    // Registers a photo picker activity launcher in single-select mode.
//    private ActivityResultLauncher<PickVisualMediaRequest> pickMediaLauncher =
//            registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
//                // Callback is invoked after the user selects a media item or closes the
//                // photo picker.
//                if (uri != null) {
//                    Log.d("PhotoPicker", "Selected URI: " + uri);
//                    String fileExtension = UriUtils.getFileExtension(getActivity(), uri);
//
//                    Log.d("PhotoPicker", "Selected URI filePath: 2:" + fileExtension);
//                    String filePath = FkhUriFixUtils.fixFilePath(this, uri, fileExtension);
//                    if (com.blankj.utilcode.util.StringUtils.isEmpty(filePath)) {
//                        ToastUtils.showLong("选择图片失败");
//                    }
//                    billImages.add(billImages.size() - 1, filePath);//到倒数第二个位置增加
//                    tagAdapter.notifyDataChanged();
//                } else {
//                    Log.d("PhotoPicker", "No media selected");
//                    ToastUtils.showLong("No media selected");
//                }
//            });


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        diaryId = getIntent().getIntExtra("diaryId", -1);
        selectDay = getIntent().getStringExtra("selectDay");
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayout() {
        return R.layout.diary_edit;
    }

    @Override
    protected void initView() {
        setSupportToolbarBack(toolbar);
        initImagePick();
        if (this.diaryId != -1) {
            diary = LitePal.find(Diary.class, diaryId);
            this.selectDay = diary.getDay();
            etTitle.setText(diary.getTitle());
            etContent.setText(diary.getContent());
            if (StringUtils.isNotEmpty(diary.getImages())) {
                String[] imageArray = diary.getImages().split(",");
//                billImages.clear();
                billImages.addAll(billImages.size() - 1, Arrays.asList(imageArray));
                tagAdapter.notifyDataChanged();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_diary_edit, menu);
        return true;
    }

    @Override
    public void initBinder() {
        toolbar = findViewById(R.id.toolbar);
        etTitle = findViewById(R.id.etTitle);
        etContent = findViewById(R.id.etContent);
//        pickImage = findViewById(R.id.pickImage);
//        pickImage.setOnClickListener(this);
        addImage = findViewById(R.id.addImage);
    }

    private void saveDiary() {
        String title = etTitle.getText().toString();
        String content = etContent.getText().toString();
        if (StringUtils.isEmpty(title) && StringUtils.isEmpty(content)) {
            Toast.makeText(DiaryAddActivity.this, "The title and content cannot both be empty.", Toast.LENGTH_SHORT).show();
            return;
        }
        if (diaryId == -1) {
            Diary diary = new Diary();
            diary.setTitle(title);
            diary.setContent(content);
            diary.setCreateTime(System.currentTimeMillis());
            diary.setUpdateTime(diary.getCreateTime());
            diary.setDay(this.selectDay);
            String s1 = this.selectDay + " " + TimeUtils.millis2String(diary.getCreateTime(), "HH:mm:00");
            diary.setDayTime(TimeUtils.string2Millis(s1));
            diary.setMood(1);
            diary.setType(1);
            if (billImages.size() > 0) {
                diary.setImages(StringUtils.join(",", getBillImages()));
            }
            diary.save();
            etTitle.setText("");
            etContent.setText("");
        } else {
            diary.setTitle(title);
            diary.setContent(content);
            diary.setUpdateTime(System.currentTimeMillis());
            if (billImages.size() > 0) {
                diary.setImages(StringUtils.join(",", getBillImages()));
            }
            diary.update(diary.getId());
        }
        Toast.makeText(DiaryAddActivity.this, "Saved successfully", Toast.LENGTH_SHORT).show();
        setResult(RESULT_OK);
        finish();
    }

    List<String> getBillImages() {
        List<String> bills = new ArrayList<>();
        for (String s : billImages) {
            if (!ADD_TAG.equals(s)) {
                bills.add(s);
            }
        }
        return bills;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.action_save) {
            saveDiary();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private final int PICK_IMAGE_CODE = 900;//1从相册选取 2 拍照
    private final int TAKE_PHOTO_CODE = 901;//1从相册选取 2 拍照

    private void pickImage() {
        if (getBillImages().size() >= PIC_MAX_LIMIT) {
            ToastUtils.showShort("最多上传" + PIC_MAX_LIMIT + "张图片");
            return;
        }
        Intent intentPhoto = new Intent(Intent.ACTION_PICK);
        intentPhoto.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intentPhoto, PICK_IMAGE_CODE);

//        String mimeType = "image/*";
//        pickMediaLauncher.launch(new PickVisualMediaRequest.Builder()
//                .setMediaType(new ActivityResultContracts.PickVisualMedia.SingleMimeType(mimeType))
//                .build());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_CODE) {
            if (data == null || data.getData() == null) {
                return;
            }
            Uri uri = data.getData();
            if (uri != null) {
                Log.d("PhotoPicker", "Selected URI: " + uri);
                String fileExtension = UriUtils.getFileExtension(getActivity(), uri);

                Log.d("PhotoPicker", "Selected URI filePath: 2:" + fileExtension);
                String filePath = FkhUriFixUtils.fixFilePath(this, uri, fileExtension);
                if (com.blankj.utilcode.util.StringUtils.isEmpty(filePath)) {
                    ToastUtils.showLong("选择图片失败");
                }
                billImages.add(billImages.size() - 1, filePath);//到倒数第二个位置增加
                tagAdapter.notifyDataChanged();
            } else {
                Log.d("PhotoPicker", "No media selected");
                ToastUtils.showLong("No media selected");
            }
        }
    }

    @Override
    public void onClick(View view) {
    }
}
